import {
  login,
  getUserInfo,
  getUserDetailById
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  setTime
} from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, data) {
      state.token = data
      setToken(data)
      // 存入时间戳
      setTime()
    },
    // 删除token
    delToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户资料
    setUserInfo(state, data) {
      state.userInfo = data
    },
    // 删除用户资料
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },

  actions: {
    // 登录
    async login(context, data) {
      let res = await login(data)
      console.log(res);
      context.commit('setToken', res)
    },
    // 获取用户资料
    async getUserInfo(context) {
      const res = await getUserInfo()

      const res2 = await getUserDetailById(res.userId)
      // console.log(res);
      // 拼接用户头像
      context.commit('setUserInfo', {
        ...res,
        ...res2
      })
    },
    // 退出
    logout(context) {
      context.commit('delToken')
      context.commit('removeUserInfo')
    }
  },
}
